package com.putao.web.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.putao.annotation.OperateMethodName;
import com.putao.base.BaseController;
import com.putao.domain.SysUser;
import com.putao.enums.VerifyCodeEnum;
import com.putao.feign.WebsocketFeign;
import com.putao.redis.service.IRedisService;
import com.putao.result.JsonResult;
import com.putao.result.WebsocketResult;
import com.putao.service.SysRoleService;
import com.putao.service.SysUserService;
import com.putao.utils.RandomUtils;
import com.putao.utils.SendCodeUtils;
import com.putao.utils.StringUtils;
import com.putao.utils.ThreadLocalUtil;
import com.putao.vo.UserVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;


/*
 @Author:putao
 @Date:2022-07-06 21:15:22
*/
@RestController
@RequestMapping("/users")
@RefreshScope
@Slf4j
public class UserController extends BaseController<SysUser> {

    @Autowired
    private SysUserService userService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SendCodeUtils sendCodeUtils;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private WebsocketFeign websocketFeign;


    @GetMapping("/getQrCode")
    public JsonResult getQrCode(String oldUuid) {
        String uuid = StringUtils.getUuid();
        log.error("uuid: " + uuid);
        return JsonResult.selectSuccess(userService.getQrcode(oldUuid, uuid), uuid);
    }

    @GetMapping("/getDay")
    public JsonResult getDay() {
        String userId = ThreadLocalUtil.getUserId();
        if (StringUtils.isBlank(userId)) {
            return JsonResult.argumentError("获取用户id失败，", null, null);
        }
        SysUser sysUser = userService.getById(userId);
        if (ObjectUtil.isNotEmpty(sysUser) && ObjectUtil.isNotEmpty(sysUser.getConsecutiveBkDays())) {
            return JsonResult.selectSuccess(sysUser.getConsecutiveBkDays(), null);
        }
        return JsonResult.selectNotFound(null, null);
    }

    @GetMapping("cancelLoginPc")
    public JsonResult cancelLoginPc(String key) {
        if (StringUtils.isBlank(key)) {
            return JsonResult.argumentError(key, null);
        }
        String value = redisService.get(VerifyCodeEnum.QR_CODE_TIME_OUT.join(key));
        if (StringUtils.isNotBlank(value)) {
            log.error("设置key：{}过期，发送消息给pc", VerifyCodeEnum.QR_CODE_TIME_OUT.join(key));
            // 存在表示到时了用户尚未扫码后者扫码后尚未授权，这时将二维码改为失效，删除即可或者重置时间为0
            redisService.deleteKey(VerifyCodeEnum.QR_CODE_TIME_OUT.join(key));
            websocketFeign.sendMessage(WebsocketResult.cancelLoginPc(null, key));
        } else {
            log.error("key：{} 不存在，无法执行下面流程", VerifyCodeEnum.QR_CODE_TIME_OUT.join(key));
        }
        return JsonResult.operationSuccess(key, null);
    }

    @GetMapping("/scanSuccess")
    public JsonResult scanSuccess(String username, String key) {
        String value = redisService.get(VerifyCodeEnum.QR_CODE_TIME_OUT.join(key));
        if (StringUtils.isNotBlank(value) && StringUtils.isNotBlank(username)) {
            // 说明二维码未失效，发送消息给前端，展示用户名
            websocketFeign.sendMessage(WebsocketResult.scanSuccess(username, key));
            return JsonResult.operationSuccess(username, key);
        }
        return JsonResult.argumentError(username, key);
    }

    @PostMapping("register")
    public JsonResult register(@RequestBody UserVO userVO) {
        JsonResult result = userService.register(userVO);
        if (ObjectUtil.isNotEmpty(result)) {
            return result;
        }
        return insertSuccess(userVO, null);
    }

    @GetMapping("/getByUsername")
    public JsonResult getByUsername( @RequestParam("username") String username) {
        return userService.getByUsername(username);
    }
    @GetMapping("/getByPhone")
    public JsonResult getByPhone( @RequestParam("phone") String phone) {
        return userService.getByPhone(phone);
    }

    @GetMapping("/getRolesByRoleIds")
    public JsonResult getRolesByRoleIds( @RequestParam("roleIds") String roleIds) {
        return roleService.getRolesByRoleIds(roleIds);
    }

    @GetMapping("/getUsers")
    public JsonResult getUsers() {
        List<SysUser> userList = userService.list();
        return CollectionUtil.isNotEmpty(userList) ? JsonResult.selectSuccess(userList, null) : JsonResult.selectNotFound(null, null);
    }

    @GetMapping("/getByUserId")
    public JsonResult getByUserId(String userId) {
        SysUser sysUser = userService.getById(userId);
        return ObjectUtil.isNotEmpty(sysUser) ? JsonResult.selectSuccess(sysUser, userId) : JsonResult.selectNotFound(userId, null);
    }

    @PostMapping("/increaseDays")
    public JsonResult increaseDays(@RequestBody List<SysUser> userList) {
        if (CollectionUtil.isNotEmpty(userList)) {
            boolean result = userService.updateBatchById(userList);
            if (result) {
                return updateSuccess(true, null);
            }
        }
        return updateNotFound(false, null);
    }

    /**
     * 发送验证码
     *
     * @return
     */
    @PostMapping("/sendCode")
    @ApiOperation(value = "发送验证码", notes = "发送验证码")
    @OperateMethodName(value = "发送验证码", method = "sysUser:sendCode")
    public JsonResult sendCode(@RequestBody SysUser user){
        if (StringUtils.isEmpty(user.getPhone())) {
            return argumentError(user.getPhone(), null);
        }
        String code = RandomUtils.generateCode();
        Date date = new Date();
        sendCodeUtils.sendCode(user.getPhone(), code, date);
        log.error("code : " + code);
        return operationSuccess(code, null);
    }
}
